package com.dodoke.ojserver.controller;

import com.dodoke.ojserver.bean.dto.UsersDTO;
import com.dodoke.ojserver.bean.mapper.UserMapStruct;
import com.dodoke.ojserver.bean.vo.UsersVO;
import com.dodoke.ojserver.config.Result;
import com.dodoke.ojserver.service.IUsersService;
import com.dodoke.ojserver.utils.JWTUtils;
import com.dodoke.ojserver.utils.PassToken;
import com.dodoke.ojserver.utils.UserLoginToken;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin//跨域
@Slf4j
@RestController
@RequestMapping("/users")
@Api(tags = "用户接口")
public class UsersController {

    @Autowired
    private IUsersService usersService;

    @PassToken
    @PostMapping(value = { "/login" })
    public Result login(@RequestBody UsersDTO usersDTO) {
        try{
            usersDTO.setPassword(DigestUtils.md5Hex(usersDTO.getPassword()));
            UsersVO usersVO = UserMapStruct.USER_MAPPER.usersToUsersVO(usersService.login(usersDTO));
            Map<String,String> dataMap =  new HashMap<>();
            dataMap.put("id",usersVO.getId());
            dataMap.put("name",usersVO.getUsername());
            //生成JWT的令牌
            String token = JWTUtils.getToken(dataMap);
            dataMap.put("token",token);
            return Result.success("认证成功", dataMap);
        }catch (Exception e){
            return Result.error(400, e.getMessage());
        }
    }

    //@PassToken
    @UserLoginToken
    @PostMapping("/test")
    public Map<String,Object> test(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("state",true);
        map.put("msg","请求成功!");
        return map;
    }
}
